package com.shark.lib.rebirth;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public abstract class RebirthService extends Service {
    private static final String TAG = "RebirthService";
    private SeviceStartBroadcastReceiver startBroadcastReceiver;
    private SeviceCancelBroadcastReceiver cancelBroadcastReceiver;
    private SreenBroadcastReceiver sreenBroadcastReceiver;
    protected abstract boolean needStartWorkService();

    public abstract Boolean isWorkRunning();

    public abstract void startWork();

    public abstract void stopWork();

    public abstract void onServiceKilled();

    @Override
    public IBinder onBind(Intent intent) {
        return new Messenger(new Handler()).getBinder();
    }

    private AbsServiceConnection mConnection = new AbsServiceConnection() {
        @Override
        public void onDisconnected(ComponentName name) {
            startBindDaemonServices();
        }
    };

    private void startBindDaemonServices() {
        if (needStartWorkService()) {
            Log.e(TAG, "启动守护进程服务... ");
            RebirthEnv.bindDaemonService(this, mConnection);
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();
        if (!needStartWorkService()) {
            stopSelf();
            return;
        }
        startRegisterReceiver();
        startCancelRegisterReceiver();
        startScreenReceiverListener();
        ForegroundNotificationUtils.startForegroundNotification(this);
        getPackageManager().setComponentEnabledSetting(new ComponentName(getPackageName(), WatchDogService.class.getName()),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return startService();
    }

    protected int startService() {
        startBindDaemonServices();
        if (!isWorkRunning()) {
            //业务逻辑
            startWork();
        }
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        onEnd();
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy... ");
        ForegroundNotificationUtils.deleteForegroundNotification(this);
        stopRegisterReceiver();
        stopCancelRegisterReceiver();
        stopScreenReceiverListener();
        onEnd();
    }

    protected void onEnd() {
        onServiceKilled();
        startBindDaemonServices();
    }

    public void startScreenReceiverListener() {
        if (sreenBroadcastReceiver == null) {
            sreenBroadcastReceiver = new SreenBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_USER_PRESENT);
            registerReceiver(sreenBroadcastReceiver, filter);
        }
    }

    public void stopScreenReceiverListener() {
        if (null != sreenBroadcastReceiver) {
            unregisterReceiver(sreenBroadcastReceiver);
            sreenBroadcastReceiver = null;
        }
    }

    private void stopService() {
        //RebirthEnv.safelyUnbindService(this, mConnection);
        stopWork();
        //stopSelf();
    }

    private void startCancelRegisterReceiver() {
        if (cancelBroadcastReceiver == null) {
            cancelBroadcastReceiver = new SeviceCancelBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(RebirthEnv.ACTION_CANCEL_JOB_ALARM_SUB);
            registerReceiver(cancelBroadcastReceiver, intentFilter);
        }
    }

    private void stopCancelRegisterReceiver() {
        if (cancelBroadcastReceiver != null) {
            unregisterReceiver(cancelBroadcastReceiver);
            cancelBroadcastReceiver = null;
        }
    }

    private void startRegisterReceiver() {
        if (startBroadcastReceiver == null) {
            startBroadcastReceiver = new SeviceStartBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(RebirthEnv.ACTION_START_JOB_ALARM_SUB);
            registerReceiver(startBroadcastReceiver, intentFilter);
        }
    }

    private void stopRegisterReceiver() {
        if (startBroadcastReceiver != null) {
            unregisterReceiver(startBroadcastReceiver);
            startBroadcastReceiver = null;
        }
    }

    class SeviceCancelBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            stopService();
        }
    }

    class SeviceStartBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            startService();
        }
    }

    public class SreenBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) { // 开屏
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 锁屏
                //TODO:锁屏
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解锁
                //TODO:解锁
            }
        }
    }
}
